//
//  LoginPassWordSetViewController.m
//  XTXOneToOne
//
//  Created by Canny on 2018/10/29.
//  Copyright © 2018年 WK. All rights reserved.
//

#import "LoginPassWordSetViewController.h"



@interface LoginPassWordSetViewController ()

@property (nonatomic,strong)UITextField * textField1;
@property (nonatomic,strong)UITextField * textField2;
@property (nonatomic,strong)UITextField * textField3;
@property (nonatomic,strong)UIButton * receiveCheckNumButton;
@end

@implementation LoginPassWordSetViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    [self setProperty];
    
    [self createUI];
    
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
}

-(void)setProperty{
    
    self.view.backgroundColor=RGB(255, 255, 255);
    
    [UIApplication sharedApplication].statusBarHidden = NO;
    
    self.navigationController.navigationBar.translucent = YES;
    self.navigationController.navigationBarHidden=YES;
    
    self.baseVcTitle = @"登录密码";
}


-(void)createUI{
    
    [self setTitle:@"新的登录密码" andIndex:1 andPlaceholder:@"请输入资金密码" andKeyboardType:UIKeyboardTypeDefault andSecureTextEntry:YES];
    [self setTitle:@"确认登录密码" andIndex:2 andPlaceholder:@"请输入资金密码" andKeyboardType:UIKeyboardTypeDefault andSecureTextEntry:YES];
    [self setTitle:@"短信验证码" andIndex:3 andPlaceholder:@"请输入验证码" andKeyboardType:UIKeyboardTypeNumberPad andSecureTextEntry:NO];
    
    [self.rightBtn setTitle:@"完成" forState:UIControlStateNormal];
    [self.rightBtn setTitleColor:RGB(99, 139, 219) forState:UIControlStateNormal];
    
    
}

-(void)setTitle:(NSString *)title andIndex:(NSInteger)index andPlaceholder:(NSString *)Placeholder andKeyboardType:(UIKeyboardType)type andSecureTextEntry:(BOOL)isSecureTextEntry{
    
    CGFloat H =95,T=(index-1)*95+80;
    
    UIView * bgview = [[UIView alloc]init];
    bgview.frame = CGRectMake(0, T, G_SCREENWIDTH, H);
    [self.view addSubview:bgview];
    
    UILabel *label = [[UILabel alloc] init];
    label.text = title;
    label.font = [UIFont systemFontOfSize:12];
    label.textColor = RGB(30, 63, 89);
    label.textAlignment=NSTextAlignmentLeft;
    [bgview addSubview:label];
    [label mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(bgview.mas_top).offset(20);
        make.left.equalTo(bgview.mas_left).offset(15);
        make.width.equalTo(@(120));
        make.height.equalTo(@(30));
    }];
    
    UITextField * textField=[[UITextField alloc]init];
    textField.secureTextEntry = isSecureTextEntry;
    textField.tag=500+index;
    [bgview addSubview:textField];
    [self setTextField:textField WithPlaceholder:Placeholder  and:type];
    [textField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgview.mas_bottom);
        make.left.equalTo(bgview.mas_left).offset(15);
        make.right.equalTo(bgview.mas_right).offset(-15);
        make.height.equalTo(@(50));
    }];
    if (index==1) {
        _textField1=textField;
    }else if (index==2){
        _textField2=textField;
    }else if (index==3){
        _textField3=textField;
        
        _receiveCheckNumButton = [[UIButton alloc] init];
        _receiveCheckNumButton.backgroundColor = MC_TEST_COLOR;
        [_receiveCheckNumButton setTitle:@"发送验证码"forState:UIControlStateNormal];
        [_receiveCheckNumButton setTitleColor:RGB(99, 140, 220) forState:UIControlStateNormal];
        _receiveCheckNumButton.titleLabel.font = [UIFont systemFontOfSize:12];
        //    _receiveCheckNumButton.layer.cornerRadius =5;
        //    _receiveCheckNumButton.layer.masksToBounds =YES;
        //    _receiveCheckNumButton.alpha =0.3;
        [bgview addSubview:_receiveCheckNumButton];
        _receiveCheckNumButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
        
        [_receiveCheckNumButton mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(textField.mas_centerY).offset(0);
            make.width.equalTo(@(100));
            make.right.equalTo(self.view.mas_right).offset(-15);
            make.height.equalTo(@(30));
        }];
        
        [_receiveCheckNumButton addTarget:self action:@selector(actionReceiveCheckNumButton) forControlEvents:UIControlEventTouchUpInside];
        
        
    }
    
    
    UIView * line = [[UIView alloc]init];
    [bgview addSubview:line];
    line.backgroundColor = RGB(231, 235, 238);
    [bgview addSubview:line];
    [line mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(bgview.mas_bottom).offset(-1);
        make.left.equalTo(bgview.mas_left).offset(15);
        make.right.equalTo(bgview.mas_right).offset(-15);
        make.height.equalTo(@(1));
    }];
    
    
}


-(void)setTextField:(UITextField*)textField WithPlaceholder:(NSString *)placeholder and:(UIKeyboardType)type  {
    
    
    textField.placeholder=placeholder;
    textField.borderStyle = UITextBorderStyleNone;
    textField.backgroundColor=[UIColor clearColor];
    textField.font = [UIFont systemFontOfSize:15];
    textField.textColor = RGB(40, 40, 40);
    textField.textAlignment = NSTextAlignmentLeft;
    textField.returnKeyType = UIReturnKeyDone;
    textField.keyboardType = type;
    [textField setValue:RGB(190, 190, 190) forKeyPath:@"_placeholderLabel.textColor"];
    [textField setValue:[UIFont systemFontOfSize:14] forKeyPath:@"_placeholderLabel.font"];
    [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:(UIControlEventEditingChanged)];
    
}

-(void)textFieldDidChange:(UITextField *)textField{
    textField.text= [textField.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    
    if (textField.tag==501) {
        
    }else if(textField.tag==502){
        
    }else if(textField.tag==503){
        
    }
}


#pragma mark-完成
-(void)rightAction{
    
    if (_textField1.text.length<1||_textField2.text.length<1) {
        [HUD showErrorMessage:@"请输入登录密码！"];
        return;
    }
    if (_textField3.text.length<1) {
        [HUD showErrorMessage:@"请输入验证码！"];
        return;
    }
    
    if (![_textField1.text isEqualToString:_textField2.text]) {
        [HUD showErrorMessage:@"两次输入的登录密码不一致！"];
        return;
    }
    
    
    NSString * URL = [NSString stringWithFormat:@"%@user/repwd",DEFAULTSEVERBASEURL];
    __weak __typeof(self)wself = self;
    
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:@{@"code":_textField3.text,@"password":_textField1.text,@"access_token":[LoginModel GetValue:DL_token]} SuccessBlock:^(id  _Nonnull responseObject) {
        NSDictionary * dic = responseObject;
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            
            [HUD showSuccessMessage:dic[@"msg"]];
            [wself.navigationController popViewControllerAnimated:YES];
            
        }else{
            [HUD showErrorMessage:dic[@"msg"]];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        
    }];
    
}


#pragma mark-获取验证码倒计时
- (void)actionReceiveCheckNumButton{
    
    __weak __typeof(self)wself = self;
    
    NSString * URL = [NSString stringWithFormat:@"%@verify/sms",DEFAULTSEVERBASEURL];
    
    NSString * phoneNumber = [LoginModel GetValue:DL_Phone];
    [MOLoadHttpsData PostHttpDataWithUrlStr:URL Dic:@{@"action":@"repwd",@"phone":phoneNumber} SuccessBlock:^(id  _Nonnull responseObject) {
        NSDictionary * dic = responseObject;
        NSString * code = [NSString stringWithFormat:@"%@",dic[@"code"]];
        if ([code isEqualToString:@"0"]) {
            [wself startTimer];
            [HUD showErrorMessage:dic[@"msg"]];
        }else{
            [HUD showErrorMessage:dic[@"msg"]];
        }
        
    } FailureBlock:^(id  _Nonnull error) {
        
    }];
    
}

-(void)startTimer{
    
    __weak __typeof(self)wself = self;
    
    __block int timeout=60;//倒计时时间
    dispatch_queue_t queue =dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
    dispatch_source_t _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER,0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL,0),1.0*NSEC_PER_SEC,0); //每秒执行
    dispatch_source_set_event_handler(_timer, ^{
        if(timeout<=0){//倒计时结束,关闭
            dispatch_source_cancel(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //设置界面的按钮显示根据自己需求设置
                [wself.receiveCheckNumButton setTitle:@"发送验证码"forState:UIControlStateNormal];
                wself.receiveCheckNumButton.userInteractionEnabled =YES;
                //                wself.receiveCheckNumButton.backgroundColor = [UIColor purpleColor];
            });
        }else{
            int seconds = timeout;
            NSString *strTime = [NSString stringWithFormat:@"%.2d", seconds];
            dispatch_async(dispatch_get_main_queue(), ^{
                //让按钮变为不可点击的灰色
                //                wself.receiveCheckNumButton.backgroundColor = [UIColor grayColor];
                wself.receiveCheckNumButton.userInteractionEnabled =NO;
                //设置界面的按钮显示根据自己需求设置
                [UIView beginAnimations:nil context:nil];
                [UIView setAnimationDuration:1];
                [wself.receiveCheckNumButton setTitle:[NSString stringWithFormat:@"%@秒后重发",strTime]forState:UIControlStateNormal];
                [UIView commitAnimations];
            });
            timeout--;
        }
    });
    dispatch_resume(_timer);
}


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
